
'use client'

import { useCallback, useContext, useEffect, useMemo, useRef, useState } from 'react';
import styles from './index.module.scss';
import cName from 'classnames';
import { IHeroInfo } from '@/typing/hero';
import { useClickAway } from 'ahooks';
import { defaultPercentage, defaultSpringScale, initSpringTranslate, initTransformElementCalc } from './store';
import { HeroProviderContext } from '@/app/[lng]/heros/hero-providers';
import Image from 'next/image';
import { generateRandomInteger } from '@/util/index';

const multiple = 20;

const HeroCard = (props: IHeroInfo) => {
  const { top_img = '' } = props;

  let repositionTimer: any = null;

  const { activeHero = {}, setActiveHero = () => { } } = useContext(HeroProviderContext);

  const wrapperRef = useRef<any>(null);
  const elementRef = useRef<any>(null);
  const imgRef = useRef<any>(null);
  const activeRef = useRef<any>(null);

  // 是否选中
  const [active, setActive] = useState(false);
  activeRef.current = active;

  const randomImgIndex = useMemo(() => {
    return generateRandomInteger(1, 4)
  }, [])

  const [transformElementCalc, setTransformElementCalc] = useState(initTransformElementCalc);
  // 点击移动动画 配置
  const [springTranslate, setSpringTranslate] = useState(initSpringTranslate);

  const [springScale, setSpringScale] = useState(defaultSpringScale);
  const [percentage, setPercentage] = useState(defaultPercentage);

  const initPageSetting = () => {
    setActive(false);
    setTransformElementCalc(initTransformElementCalc);
    setSpringTranslate(initSpringTranslate);
    setSpringScale(defaultSpringScale);
    setPercentage(defaultPercentage);
  }

  const initPageTimer = () => {
    clearTimeout(repositionTimer)
  }

  useClickAway(() => {
    initPageSetting();
  }, wrapperRef);

  const setCenter = () => {
    const rect = wrapperRef.current.getBoundingClientRect();
    const view = document.documentElement;

    let scaleW = (window.innerWidth / rect.width) * 0.9;
    let scaleH = (window.innerHeight / rect.height) * 0.9;
    let scaleF = 1.75;

    const delta = {
      x: Math.round(view.clientWidth / 2 - rect.x - rect.width / 2),
      y: Math.round(view.clientHeight / 2 - rect.y - rect.height / 2),
    };

    setSpringTranslate({
      x: delta.x,
      y: delta.y,
    });

    setSpringScale(Math.min(scaleW, scaleH, scaleF))
  };

  const handleViewCard = () => {
    if (active) {
      setActiveHero({});
      setActive(false);
    } else {
      setActiveHero(props);
      setActive(true);
    }
  }

  const noVfx = useMemo(() => {
    if (activeHero?.id && props.id !== activeHero?.id) {
      return true;
    }
    return false
  }, [activeHero, props]);

  const getTranslateRate = () => {
    let x = initTransformElementCalc.calcX;
    let y = initTransformElementCalc.calcY;
    if (activeHero?.id && activeHero?.id !== props.id) {
      // pass
    } else {
      x = transformElementCalc.calcX;
      y = transformElementCalc.calcY;
    }
    return {
      x,
      y
    }
  }

  const dynamicElementStyles = useMemo(() => {
    return {
      '--translate-rate-x': `${getTranslateRate().x}deg`,
      '--translate-rate-y': `${getTranslateRate().y}deg`,
      // 如果不是选中则不展示焦距状态
      '--translate-x': `${active ? springTranslate.x : initSpringTranslate.x}px`,
      '--translate-y': `${active ? springTranslate.y : initSpringTranslate.y}px`,
      '--card-scale': `${active ? springScale : defaultSpringScale}`,
    }
  }, [transformElementCalc, springTranslate, springScale, active, activeHero]);

  const dynamicImgStyles = useMemo(() => {
    return {
      '--per': `${percentage}%`,
      'backgroundImage': `url(https://images.weserv.nl/?url=${top_img})`,
    }
  }, [percentage, top_img]);


  const reposition = () => {
    clearTimeout(repositionTimer);
    repositionTimer = setTimeout(() => {
      if (activeRef.current) {
        setCenter();
      }
    }, 300);
  };

  useEffect(() => {
    if (active) {
      setCenter();
    }
  }, [active])

  useEffect(() => {
    const mouseOverContainer = wrapperRef.current;
    const element = elementRef.current;

    function transformElement(x: number, y: number) {
      console.log('transformElement');
      let box = element!.getBoundingClientRect();
      const calcX = -(y - box.y - box.height / 2) / multiple;
      const calcY = (x - box.x - box.width / 2) / multiple;
      const percentage = parseInt((x - box.x) / box.width * 1000) / 10;

      setTransformElementCalc({
        calcX,
        calcY
      })
      setPercentage(percentage);
    }

    function requestAnimationFrameTransformElement(e) {
      console.log('requestAnimationFrameTransformElement');
      window.requestAnimationFrame(function () {
        console.log('requestAnimationFrame');
        transformElement(e.clientX, e.clientY);
      });
    }

    function init() {
      window.requestAnimationFrame(function () {
        setTransformElementCalc({
          calcX: 0,
          calcY: 0
        })
      });
    }

    console.log('mouseOverContainer', mouseOverContainer);
    mouseOverContainer.addEventListener("mousemove", requestAnimationFrameTransformElement);
    mouseOverContainer.addEventListener("mouseleave", init);

    window.addEventListener('resize', setCenter);
    window.addEventListener('scroll', reposition);

    return () => {
      initPageTimer();

      mouseOverContainer.removeEventListener("mousemove", requestAnimationFrameTransformElement);
      mouseOverContainer.removeEventListener("mouseleave", init);

      window.removeEventListener('resize', setCenter);
      window.removeEventListener('scroll', reposition);
    }
  }, []);

  return (
    <div
      ref={wrapperRef}
      className={
        cName("lg:w-1/4 sm:w-1/3 p-4", styles['wrapper'], {
          [styles['active']]: active,
          [styles['no-vfx']]: noVfx,
        })
      }
      onClick={() => {
        handleViewCard()
      }}
    >
      <div ref={elementRef} className={styles['element']} style={{ ...dynamicElementStyles }}>
        <Image
          src={`/images/hero/holo-texture-${randomImgIndex}.webp`}
          fill={true}
          style={{ objectFit: "cover", mixBlendMode: "color-dodge", borderRadius: '10px' }}
          alt="img"
        />
        <div ref={imgRef} className={styles['g-img']} style={{ ...dynamicImgStyles }}></div>
      </div>
    </div>
  )
}
export default HeroCard